package aos.server;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;
import java.util.StringTokenizer;
import java.util.Vector;

import org.apache.log4j.Logger;

/**
 * This class manages the server properties stored in the server.properties file.
 * 
 * @author Yannic
 *
 */
public class ServerProperties extends Properties {
	
	private static final String FILENAME = "server.properties";
	public static final String ACCEPTED_USERS = "accepted-users";
	public static final String APPLICATION_NAME = "application-name";
	public static final String COMM_PORT = "comm-port";
	public static final String COMM_RATE = "comm-rate";
	public static final String COMM_DATABITS = "comm-databits";
	public static final String COMM_STOPBITS = "comm-stopbits";
	public static final String COMM_PARITY = "comm-parity";
	
	private static ServerProperties instance = null;
	Vector<String> acceptedUserList = new Vector<String>();
	
	Logger logger = Logger.getLogger(ServerProperties.class);
	
	
	public static ServerProperties getInstance() {
		 if(instance == null) {
			 instance = new ServerProperties();
		 }
		 return instance;
		 
	}
	
	private ServerProperties() {
		FileInputStream inf = null;
		try {
			inf = new FileInputStream(FILENAME);
			super.load(inf);
			logger.info("Server properties loaded from " + FILENAME);
		} catch (FileNotFoundException e) {
			logger.fatal(FILENAME + " has not been found. Unable to load server properties.", e);
			logger.fatal("System exit with error");
			System.exit(-1);
		} catch (IOException e) {
			logger.fatal("Unable to load properties from " + FILENAME + ".");
			logger.fatal("System exit with error");
			System.exit(-1);
		}
		
		StringTokenizer tokenizer = new StringTokenizer(super.getProperty(ACCEPTED_USERS), ",");
		while(tokenizer.hasMoreTokens()){
			acceptedUserList.add(tokenizer.nextToken());
			logger.info("Added " + acceptedUserList.lastElement() + " to the list of accepted users");
		}
	}
	
	public int getIntegerProperties(String prop) {
		String value = super.getProperty(prop);
		int result = 0; 
			try {
				result = Integer.valueOf(value);
			} catch(NumberFormatException e) {
				logger.fatal("Unable to get an integer value from " + prop + ":" + value);
				logger.fatal("System exit with error");
				System.exit(-1);
			}
			logger.debug("Server properties: " + prop + " = " + result);
		return result;
	}
	
	public boolean isAcceptedUser(String user){
		return acceptedUserList.contains(user);
	}
}
